<?php
require_once($_SERVER['DOCUMENT_ROOT'].'../system/config.php');
require_once($INCLUDE_DIR.'cametrics.helper.php');

function geocodeByAddress($address){
	/*
		 * Code borrowed from http://www.timshowers.com/2008/08/php-geocoding-tutorial-with-the-google-maps-api-part-one

	 */
	//Three parts to the querystring: q is address, output is the format (
	//$key = "YOUR KEY HERE";
	$address = urlencode($address);
	$url = "http://maps.google.com/maps/geo?q=".$address."&output=csv";

	$ch = curl_init();

	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_HEADER,0);
	curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

	$data = curl_exec($ch);
	curl_close($ch);

	//Check our Response code to ensure success
	if (substr($data,0,3) == "200")
	{
		$data = explode(",",$data);

		$precision = $data[1];
		$latitude = $data[2];
		$longitude = $data[3];

		$rtn = array();
		$rtn['latitude'] = $latitude;
		$rtn['longitude'] = $longitude;
		$rtn['precision'] = $precision;

		return $rtn;
	}
	else {
		//echo "Error in geocoding! Http error ".substr($data,0,3);
		return FALSE;
	}
}


// check for username
if (isset($_REQUEST['username']) && $_REQUEST['username'] != '') {
	$username = $_REQUEST['username'];
	file_put_contents($errorlog,"username: $username".PHP_EOL, FILE_APPEND);
}
else {
	header('HTTP/1.1 400 Bad Request');
	file_put_contents($errorlog,"Missing username.".PHP_EOL, FILE_APPEND);
	die('Missing required field: username');
}

// check for password
if (isset($_REQUEST['password']) && $_REQUEST['password'] != '') {
	$password = md5($_REQUEST['password']);
	file_put_contents($errorlog,"password set".PHP_EOL, FILE_APPEND);
}
else {
	header('HTTP/1.1 400 Bad Request');
	file_put_contents($errorlog,"Missing password.".PHP_EOL, FILE_APPEND);
	die('Missing required field: password');
}
// open database
$db = new PDO("sqlite:".$DATABASE);

// check login credentials
$query = "SELECT username, usergroup FROM user WHERE username = :user AND password = :pass";
$select = $db->prepare($query);
if (!$select)  {
	header('HTTP/1.1 500 Internal Server Error');
	file_put_contents($errorlog,"Error preparing db statement.".PHP_EOL, FILE_APPEND);
	die('there is a problem with the database');
}
else {
	$select->execute(array(':user'=>$username, ':pass'=>$password));
	$row = $select->fetch(PDO::FETCH_ASSOC);
	if (!$row || count($row) < 2) {
		header('HTTP/1.1 401 Unauthorized');
		file_put_contents($errorlog,"User not authenticated. row false or < 2".PHP_EOL, FILE_APPEND);
		die('User could not be authenticated.');
	}
	// redundant check...
	else if ($row['username'] != $username) {
		header('HTTP/1.1 401 Unauthorized');
		file_put_contents($errorlog,"User not match".PHP_EOL, FILE_APPEND);
		die('User could not be authenticated.');
	}
	else {
		$username = $row['username'];
		$groupname = $row['usergroup'];
	}

}
$db = null;

// check for datetime
if (isset($_REQUEST['datetime']) && $_REQUEST['datetime'] != '') {
	$dtmp = $_REQUEST['datetime'];

	date_default_timezone_set('PDT');

	$utime = strtotime($dtmp);
	if (!$utime) {
		header('HTTP/1.1 400 Bad Request');
		file_put_contents($errorlog,"Bad format date".PHP_EOL, FILE_APPEND);
		die('Incorrect format: datetime');
	}

	$dt = date('Y-m-d H:i:s', $utime);


	$temp = explode(" ", $dt);
	$d = $temp[0];
	$t = $temp[1];
	$title = $d;
	file_put_contents($errorlog,"$d,$t set".PHP_EOL, FILE_APPEND);
}
else {
	header('HTTP/1.1 400 Bad Request');
	file_put_contents($errorlog,"Missing datetime date".PHP_EOL, FILE_APPEND);
	die('Missing required field: datetime');
}
// check for location data
if (isset($_REQUEST['latitude']) && isset($_REQUEST['longitude']) && $_REQUEST['latitude'] != '' && $_REQUEST['longitude'] != '') {
	$latitude = $_REQUEST['latitude'];
	$longitude = $_REQUEST['longitude'];
	file_put_contents($errorlog,"location: $latitude,$longitude".PHP_EOL, FILE_APPEND);
}
else if (isset($_REQUEST['geotag']) && $_REQUEST['geotag'] != '') {
	$geotag = $_REQUEST['geotag'];
	file_put_contents($errorlog,"geotag: $geotag".PHP_EOL, FILE_APPEND);
	$flickrtaglist .= ",".$geotag;
	$loc = geocodeByAddress($geotag);
	if ($loc != false) {
		$latitude = $loc['latitude'];
		$longitude = $loc['longitude'];
	}
}
else {
	header('HTTP/1.1 400 Bad Request');
        die('Missing required field: longitude+latitude or geotag');
}

$type = strtolower($type);
$username = strtolower($username);
$groupname = strtolower($groupname);

Cametrics::measure($username.".contributions.location.all", $longitude.",".$latitude, 'location');
Cametrics::measure($groupname.".contributions.location.all", $longitude.",".$latitude, 'location');
Cametrics::measure("contributions.location.all", $longitude.",".$latitude, 'location');

Cametrics::measure($username.".contributions.location.".$type, $longitude.",".$latitude, 'location');
Cametrics::measure($groupname.".contributions.location.".$type, $longitude.",".$latitude, 'location');
Cametrics::measure("contributions.location.".$type, $longitude.",".$latitude, 'location');

Cametrics::measure("$groupname.contributions.location.$username.$type", $longitude.",".$latitude, 'location');
Cametrics::measure("contributions.location.$username.$type", $longitude.",".$latitude, 'location');

Cametrics::measure("$groupname.contributions.location.$username.all", $longitude.",".$latitude, 'location');
Cametrics::measure("contributions.location.$username.all", $longitude.",".$latitude, 'location');

file_put_contents(dirname(__FILE__).'/../logs/upload_location.log', 
	$dt.': "'.$tags.'" ('.$latitude.' '.$longitutde.')'.PHP_EOL, 
	FILE_APPEND);

Cametrics::measure($username.".contributions.type", $type, 'string');
Cametrics::measure($username.".contributions.time", $dt, 'datetime');

Cametrics::measure($groupname.".contributions", $username, 'string');   
Cametrics::measure($groupname.".contributions.type", $type, 'string');
Cametrics::measure($groupname.".contributions.time", $dt, 'datetime');
Cametrics::measure("contributions.group", $groupname, 'string');


Cametrics::measure("contributions", $username, 'string');
Cametrics::measure("contributions.type", $type, 'string');
Cametrics::measure("contributions.time", $dt, 'datetime');
?>
